package www.dashu.com.auth.config;

import www.dashu.com.domain.SysApp;
import www.dashu.com.service.SysAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MyDetailService implements ClientDetailsService, ClientRegistrationService
{
    @Autowired
    SysAppService appService;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException
    {
        Map<String, Object> queryMaps = new HashMap<>();
        queryMaps.put("apiPath", clientId);
        List<SysApp> appList = appService.findAll(queryMaps);
        BaseClientDetails details = new BaseClientDetails();
        if (!StringUtils.isEmpty(appList) && appList.size() > 0) {
            String _clientId = appList.get(0).getApiPath();
            details.setClientId(_clientId);
            details.setClientSecret(passwordEncoder.encode("123456"));
            details.setAuthorizedGrantTypes(Arrays.asList("password", "refresh_token"));
            details.setScope(Arrays.asList("all"));
            details.setAccessTokenValiditySeconds(3600 * 24);
            details.setRefreshTokenValiditySeconds(3600 * 24 * 7);
        }
        return details;
    }

    @Override
    public void addClientDetails(ClientDetails clientDetails) throws ClientAlreadyExistsException
    {

    }

    @Override
    public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException
    {

    }

    @Override
    public void updateClientSecret(String clientId, String secret) throws NoSuchClientException
    {

    }

    @Override
    public void removeClientDetails(String clientId) throws NoSuchClientException
    {

    }

    @Override
    public List<ClientDetails> listClientDetails()
    {
        return null;
    }
}
